#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFERSIZE 512

void debug(char *mess, char *param, int n)
{
    if (n == -1)
    {
        perror(mess);
        exit(1);
    }
}

int main(int ac, char **av)
{
    int in_fd, out_fd, n_chars;
    char buf[BUFFERSIZE];
    if (ac != 3)
    {
        fprintf(stderr, "Usage: %s source destination\n", av[0]);
        exit(1);
    }
    in_fd = open(av[1], O_RDONLY);
    debug("Open source error", av[1], in_fd);
    out_fd = open(av[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
    debug("Create destination error", av[2], out_fd);
    while (n_chars = read(in_fd, buf, BUFFERSIZE))
    {
        if (n_chars == -1)
            debug("Read error", av[1], -1);
        if (write(out_fd, buf, n_chars) != n_chars)
            debug("Write error", av[2], -1);
    }
    close(in_fd);
    close(out_fd);
    unlink(av[1]); // 删除原文件
    return 0;
}